package com.tomecode.tools.maven.settings.gui.frm;

import java.net.URL;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.grouplayout.GroupLayout;
import org.eclipse.swt.layout.grouplayout.LayoutStyle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.tomecode.tools.maven.settings.config.MavenVersion;
import com.tomecode.tools.maven.settings.gui.frm.loading.FrmTestUrl;
import com.tomecode.tools.maven.settings.gui.images.ImageFactory;
import com.tomecode.tools.maven.settings.gui.utils.GuiUtils;
import com.tomecode.tools.maven.settings.gui.utils.SWTResourceManager;
import com.tomecode.tools.maven.settings.model.Mirror;
import com.tomecode.tools.maven.settings.model.MirrorOfLayouts;

/**
 * Dialog for editing server
 * 
 * @author Tomas Frastia
 * @see http://www.tomecode.com or
 *      http://code.google.com/p/maven-settings-editor/
 * 
 */
public final class FrmMirrors extends Dialog {

	private Mirror newMirror;
	private Shell shlMirrors;
	private Text textID;
	private Text textName;
	private Text textURL;
	private Text textMirrorOf;
	private List<Mirror> listOfMirrors;
	private Mirror existsMirror;
	private Label labelWarning;
	private Text textLayout;
	private Button buttonTestUrl;

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public FrmMirrors(Shell parent, List<Mirror> listOfMirrors) {
		super(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
		setText("Mirror");
		this.listOfMirrors = listOfMirrors;
	}

	/**
	 * Open the dialog.
	 * 
	 * @param existsServer
	 *            if not null then editing selected server
	 * @return the result
	 */
	public final Mirror open(Mirror existsMirror, MavenVersion version) {
		createContents(existsMirror, version);
		shlMirrors.open();
		shlMirrors.layout();
		Display display = getParent().getDisplay();
		while (!shlMirrors.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return newMirror;
	}

	/**
	 * Create contents of the dialog.
	 */
	private final void createContents(Mirror existsMirror, MavenVersion version) {
		shlMirrors = new Shell(getParent(), getStyle());
		shlMirrors.setImage(ImageFactory.MAVEN_SETTINGS_EDITOR_16);
		shlMirrors.setSize(687, 344);

		Composite composite = new Composite(shlMirrors, SWT.NONE);
		final Button btnSave = new Button(composite, SWT.NONE);

		final Mirror resultMirror;

		if (existsMirror == null) {
			resultMirror = new Mirror();
			shlMirrors.setText("New Mirror");
			btnSave.setEnabled(false);
		} else {
			resultMirror = new Mirror(existsMirror);
			shlMirrors.setText("Edit Mirror");
			btnSave.setEnabled(true);
		}

		GroupLayout gl_shlMirrors = new GroupLayout(shlMirrors);
		gl_shlMirrors.setHorizontalGroup(gl_shlMirrors.createParallelGroup(GroupLayout.LEADING).add(composite, GroupLayout.DEFAULT_SIZE, 681, Short.MAX_VALUE));
		gl_shlMirrors.setVerticalGroup(gl_shlMirrors.createParallelGroup(GroupLayout.TRAILING).add(GroupLayout.LEADING, composite, GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE));

		Group group = new Group(composite, SWT.NONE);
		group.setLayout(null);

		Label lblURL = new Label(group, SWT.NONE);
		lblURL.setBounds(12, 77, 142, 13);
		lblURL.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));
		lblURL.setText("URL");

		Label lblMirrorOf = new Label(group, SWT.NONE);
		lblMirrorOf.setBounds(12, 103, 142, 13);
		lblMirrorOf.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));
		lblMirrorOf.setText("MirrorOf");

		textID = new Text(group, SWT.BORDER);
		textID.setBounds(158, 25, 477, 19);
		textID.setText(GuiUtils.formateNull(resultMirror.getId()));
		textID.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultMirror.setId(textID.getText());
				if (resultMirror.getId().trim().length() == 0) {
					labelWarning.setText("Mirror ID can't be empty");
					btnSave.setEnabled(false);
				} else {
					if (existsMirrorId(resultMirror)) {
						labelWarning.setText("Mirror ID already exists");
						btnSave.setEnabled(false);
					} else {
						labelWarning.setText("");
						btnSave.setEnabled(true);
					}
				}
			}
		});

		textName = new Text(group, SWT.BORDER);
		textName.setBounds(158, 51, 477, 19);
		textName.setText(GuiUtils.formateNull(resultMirror.getName()));
		textName.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultMirror.setName(textName.getText());
			}
		});

		textURL = new Text(group, SWT.BORDER);
		textURL.setBounds(158, 77, 433, 19);
		textURL.setText(GuiUtils.formateNull(resultMirror.getUrl()));
		textURL.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultMirror.setUrl(textURL.getText());
				if (textURL.getText().trim().length() != 0) {
					try {
						new java.net.URL(textURL.getText());
						buttonTestUrl.setEnabled(true);
					} catch (Exception ex) {
						buttonTestUrl.setEnabled(false);
					}
				} else {
					buttonTestUrl.setEnabled(false);
				}
			}
		});

		textMirrorOf = new Text(group, SWT.BORDER);
		textMirrorOf.setBounds(158, 103, 477, 19);
		textMirrorOf.setText(GuiUtils.formateNull(resultMirror.getMirrorOf()));
		textMirrorOf.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultMirror.setMirrorOf(textMirrorOf.getText());
			}
		});
		Button btnCancel = new Button(composite, SWT.NONE);
		btnCancel.addSelectionListener(new SelectionAdapter() {
			@Override
			public final void widgetSelected(SelectionEvent e) {
				shlMirrors.close();
			}
		});
		// if (GuiUtils.isWindows()) {
		// btnServerCancel.setBounds(424, 237, 94, 30);
		// }
		btnCancel.setText("Cancel");

		btnSave.addSelectionListener(new SelectionAdapter() {
			@Override
			public final void widgetSelected(SelectionEvent e) {
				newMirror = resultMirror;
				shlMirrors.close();
			}
		});

		btnSave.setText("Save");
		GroupLayout gl_composite = new GroupLayout(composite);
		gl_composite.setHorizontalGroup(gl_composite
				.createParallelGroup(GroupLayout.TRAILING)
				.add(gl_composite.createSequentialGroup().addContainerGap(485, Short.MAX_VALUE).add(btnSave, GroupLayout.PREFERRED_SIZE, 94, GroupLayout.PREFERRED_SIZE).addPreferredGap(LayoutStyle.RELATED)
						.add(btnCancel, GroupLayout.PREFERRED_SIZE, 94, GroupLayout.PREFERRED_SIZE).addContainerGap()).add(GroupLayout.LEADING, group, GroupLayout.DEFAULT_SIZE, 681, Short.MAX_VALUE));
		gl_composite.setVerticalGroup(gl_composite.createParallelGroup(GroupLayout.LEADING).add(
				gl_composite.createSequentialGroup().add(group, GroupLayout.PREFERRED_SIZE, 267, GroupLayout.PREFERRED_SIZE).add(13).add(gl_composite.createParallelGroup(GroupLayout.TRAILING).add(btnCancel).add(btnSave)).addContainerGap()));

		Label labelHelpID = new Label(group, SWT.NONE);
		labelHelpID.setBounds(653, 28, 16, 16);
		labelHelpID.setToolTipText("A unique identifier");
		labelHelpID.setImage(ImageFactory.HELP);

		Label labelHelpName = new Label(group, SWT.NONE);
		labelHelpName.setBounds(653, 54, 16, 16);
		labelHelpName.setToolTipText("The optional name that describes the mirror.");
		labelHelpName.setImage(ImageFactory.HELP);

		Label labelHelpURL = new Label(group, SWT.NONE);
		labelHelpURL.setBounds(653, 77, 16, 16);
		labelHelpURL.setToolTipText("The URL of the mirror repository.");
		labelHelpURL.setImage(ImageFactory.HELP);

		Label labelHelpMirrorOf = new Label(group, SWT.NONE);
		labelHelpMirrorOf.setBounds(653, 103, 16, 16);
		labelHelpMirrorOf.setToolTipText("The server ID of the repository being mirrored, eg \"central\". This MUST NOT match the mirror id.");
		labelHelpMirrorOf.setImage(ImageFactory.HELP);

		Label lblName = new Label(group, SWT.NONE);
		lblName.setBounds(12, 54, 142, 13);
		lblName.setText("Name");
		lblName.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));

		Label lblId = new Label(group, SWT.NONE);
		lblId.setBounds(12, 28, 142, 13);
		lblId.setText("ID");
		lblId.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));

		labelWarning = new Label(group, SWT.NONE);
		labelWarning.setBounds(12, 232, 657, 13);
		labelWarning.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));

		buttonTestUrl = new Button(group, SWT.NONE);
		buttonTestUrl.setEnabled(textURL.getText().trim().length() != 0);
		buttonTestUrl.addSelectionListener(new SelectionAdapter() {
			@Override
			public final void widgetSelected(SelectionEvent e) {
				FrmTestUrl frmTestUrl = new FrmTestUrl(shlMirrors);
				try {
					String text = frmTestUrl.open(new URL(textURL.getText()));
					if (text == null) {
						labelWarning.setText("");
					} else {
						labelWarning.setText(text);
					}
				} catch (Exception e1) {
				}

			}
		});
		buttonTestUrl.setBounds(597, 77, 38, 19);
		buttonTestUrl.setText("...");

		if (version == MavenVersion.V30) {

			Label lblLayout = new Label(group, SWT.NONE);
			lblLayout.setText("Layout");
			lblLayout.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));
			lblLayout.setBounds(12, 131, 142, 13);

			final Combo comboMirrorOfLayout = new Combo(group, SWT.NONE | SWT.READ_ONLY);
			comboMirrorOfLayout.setItems(new String[] { "", "default", "legacy" });
			if (resultMirror.getMirrorOfLayouts() == MirrorOfLayouts.EMPTY) {
				comboMirrorOfLayout.select(0);
			} else if (resultMirror.getMirrorOfLayouts() == MirrorOfLayouts.DEFAULT) {
				comboMirrorOfLayout.select(1);
			} else if (resultMirror.getMirrorOfLayouts() == MirrorOfLayouts.LEGACY) {
				comboMirrorOfLayout.select(2);
			}
			comboMirrorOfLayout.addSelectionListener(new SelectionAdapter() {
				@Override
				public final void widgetSelected(SelectionEvent e) {
					resultMirror.setMirrorOfLayouts(comboMirrorOfLayout.getItem(comboMirrorOfLayout.getSelectionIndex()));
				}
			});
			comboMirrorOfLayout.setBounds(158, 155, 477, 21);

			Label lblMirrorOfLayouts = new Label(group, SWT.NONE);
			lblMirrorOfLayouts.setText("Mirror Of Layouts");
			lblMirrorOfLayouts.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));
			lblMirrorOfLayouts.setBounds(12, 158, 142, 13);

			Label labelHelpLayout = new Label(group, SWT.NONE);
			labelHelpLayout.setToolTipText("The layout of the mirror repository. Since Maven 3.");
			labelHelpLayout.setImage(ImageFactory.HELP);
			labelHelpLayout.setBounds(653, 132, 16, 14);

			Label label_1 = new Label(group, SWT.NONE);
			label_1.setToolTipText("The layouts of repositories being mirrored. This value can be used to restrict the usage of the mirror to repositories with a matching layout (apart from a matching id). Since Maven 3. ");
			label_1.setImage(ImageFactory.HELP);
			label_1.setBounds(653, 155, 16, 14);

			textLayout = new Text(group, SWT.BORDER);
			textLayout.setText(GuiUtils.formateNull(resultMirror.getLayout()));
			textLayout.addKeyListener(new KeyAdapter() {
				@Override
				public final void keyReleased(KeyEvent e) {
					resultMirror.setLayout(textLayout.getText());
				}
			});
			textLayout.setBounds(158, 128, 477, 19);

		}

		composite.setLayout(gl_composite);
		shlMirrors.setLayout(gl_shlMirrors);

	}

	/**
	 * whether, mirror id already exits in list of mirrors id
	 * 
	 * @param resultMirror
	 * @return
	 */
	private final boolean existsMirrorId(Mirror resultMirror) {
		for (Mirror mirror : listOfMirrors) {
			if (existsMirror != null) {
				if (!existsMirror.equals(mirror)) {
					if (GuiUtils.formateNull(mirror.getId()).trim().equalsIgnoreCase(resultMirror.getId().trim())) {
						return true;
					}
				}
			} else {
				if (GuiUtils.formateNull(mirror.getId()).trim().equalsIgnoreCase(resultMirror.getId().trim())) {
					return true;
				}
			}
		}
		return false;
	}
}
